<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomAction from './components/RoomAction.vue'
import RoomMessage from './components/RoomMessage.vue'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'

import { io } from 'socket.io-client'
import type { Socket } from 'socket.io-client'
import { onMounted } from 'vue'
import { onUnmounted } from 'vue'
import type { Message, TimeMessages } from '@/types/room'
import { ref } from 'vue'

import { MsgType, OrderType } from '@/enums/index'
import { getCousultOrderDetail } from '@/services/consult'
import type { ConsultOrderItem, Image } from '@/types/consult'
import { nextTick } from 'vue'
import { showToast } from 'vant'

const userStore = useUserStore()
const route = useRoute()

let socket: Socket

// 页面渲染的扁平化消息列表数据
const list = ref<Message[]>([])

const time = ref('')

// 是否是初次加载的标识
const init = ref(true)

// 是否正在聊天的标识
const isChat = ref(false)

onMounted(() => {
  // 建立连接
  socket = io('https://consult-api.itheima.net', {
    auth: {
      token: `Bearer ${userStore.user?.token}`
    },
    query: {
      orderId: route.query.orderId
    }
  })
  // 监听连接是否建立成功
  socket.on('connect', () => {
    console.log('连接建立成功')
    // 每次重新连接时，需要先清空之前所有的聊天记录
    list.value = []
  })

  // 接收聊天记录
  socket.on('chatMsgList', (res: { code: number; message: string; data: TimeMessages[] }) => {
    console.log(res.data)
    isChat.value = false
    res.data.forEach((item) => {
      time.value = item.createTime
      // 每个时间分组的聊天对应的扁平化数组
      const arr = []

      // 处理时间消息
      arr.push({
        msgType: MsgType.Notify,
        msg: {
          content: item.createTime
        },
        createTime: item.createTime,
        id: item.createTime
      })
      // 处理聊天消息
      arr.push(...item.items)

      // 设置已读
      socket.emit('updateMsgStatus', arr[arr.length - 1].id)

      // list：所有时间分组的聊天对应的扁平化数组
      list.value.unshift(...arr)
    })

    // 关闭加载中效果
    loading.value = false

    // 没有数据了，提示没有更多聊天记录了
    if (res.data.length === 0) {
      showToast('没有更多聊天记录了')
    }

    // 处理滚动底部
    if (init.value) {
      nextTick(() => {
        window.scrollTo(0, window.document.body.scrollHeight)
      })
      init.value = false
    }

    console.log(list.value)
  })

  // 接收订单状态发生变化的事件
  socket.on('statusChange', () => {
    getCousultOrder()
  })

  // 接收单条聊天消息
  socket.on('receiveChatMsg', (res) => {
    isChat.value = true
    list.value.push(res)
    // 设置已读
    socket.emit('updateMsgStatus', res.id)
    // 让聊天消息滚动到底部
    nextTick(() => {
      window.scrollTo(0, document.body.scrollHeight)
    })
  })
})

onUnmounted(() => {
  // 问诊室组件卸载时，关闭连接
  socket.close()
})

// 获取问诊订单详情数据
const cousultOrder = ref({} as ConsultOrderItem)
const getCousultOrder = async () => {
  const res = await getCousultOrderDetail(route.query.orderId as string)
  cousultOrder.value = res.data
}

onMounted(() => {
  getCousultOrder()
})

// 接收子组件传递的聊天的文字内容
const sendText = (text: string) => {
  socket.emit('sendChatMsg', {
    from: userStore.user?.id,
    to: cousultOrder.value.docInfo?.id,
    msgType: MsgType.MsgText,
    msg: {
      content: text
    }
  })
}
// 接收子组件传递的聊天的图片内容
const sendImg = (img: Image) => {
  socket.emit('sendChatMsg', {
    from: userStore.user?.id,
    to: cousultOrder.value.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: {
      picture: img
    }
  })
}

// 下拉刷新状态
const loading = ref(false)
// 下拉刷新时，会触发的事件
const onRefresh = () => {
  // console.log('下拉刷新触发了')
  socket.emit('getChatMsgList', 20, time.value, route.query.orderId)
}
</script>

<template>
  <div class="room-page">
    <!-- 导航栏 -->
    <cp-nav-bar title="问诊室" />

    <!-- 问诊状态组件 -->
    <room-status :status="cousultOrder.status" :countDown="cousultOrder.countdown"></room-status>

    <!-- 消息组件 -->
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <room-message
        v-for="item in list"
        :key="item.id"
        :item="item"
        :init="init"
        :isChat="isChat"
      ></room-message>
    </van-pull-refresh>

    <!-- 底部操作组件 -->
    <room-action
      :disabled="cousultOrder.status !== OrderType.ConsultChat"
      @send-text="sendText"
      @send-img="sendImg"
    ></room-action>
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
.van-nav-bar {
  position: fixed;
  width: 100%;
  top: 0;
}
</style>
